package managedbean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import org.primefaces.event.FileUploadEvent;



@ManagedBean
@ViewScoped

public class MediaUploadManagedBean implements Serializable
{   
   
    private String imageFilePath;
    
    
    
    public MediaUploadManagedBean()
    {
        //setImageFilePath("/images/upload/in_room_dining_img.jpg");
        
    }
    
    
    
    public void handleImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException
    {
        
        try
        {           
            String filePath =  
                    FacesContext.getCurrentInstance().getExternalContext().getRealPath("images/upload");
            System.out.println("filePath is: "+filePath);
            File result = new File(filePath + System.getProperty("file.separator") + event.getFile().getFileName());
            FileOutputStream out = new FileOutputStream(result);

            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            InputStream is = event.getFile().getInputstream();

            while (true)
            {
                a = is.read(buffer);

                if (a < 0)
                {
                    break;
                }

                out.write(buffer, 0, a);
                out.flush();
            }

            out.close();
            is.close();

            imageFilePath = "/images/upload/" + event.getFile().getFileName();
            System.out.println("imagefilepath: " + imageFilePath);
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("imageFilePath", imageFilePath);
            

        }
        catch (IOException e)
        {
             FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
            e.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    
    
    public String getImageFilePath() {
        return imageFilePath;
    }

    private void setImageFilePath(String imageFilePath) {
        this.imageFilePath = imageFilePath;
    }
}
